<?php

namespace App\Library\Logic;

use App\Library\Requests\Feedback\FeedbackAddRequest;
use App\Library\Requests\Feedback\FeedbackPageRequest;
use App\Models\ShopFeedbackModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;

class ShopFeedbackLogic extends ShopFeedbackModel
{
    /**
     * paging
     * @param FeedbackPageRequest $request
     * @return array
     */
    public function paging(FeedbackPageRequest $request): array
    {
        $builder = $this->newQuery()->where('user_id', USERID)->orderByDesc('fb_id');
        $paginate = helpBuilder($builder->with('image'), $request)->paginate($request->limit);
        foreach ($paginate->items() as $v) {
            $v->img_url = $v->image->img_url ?? null;
            unsetObject($v, 'image');
        }
        return paginate($paginate);
    }

    /**
     * add
     * @param FeedbackAddRequest $request
     * @return void
     */
    public function add(FeedbackAddRequest $request): void
    {
        $pet = self::insertForModel(array_merge($this->saveCom($request), [
            'userId' => USERID,
            'createdAt' => time(),
            'updatedAt' => time(),
        ]));
        $this->saveImg($pet);
    }

    /**
     * saveCom
     * @param FeedbackAddRequest $request
     * @return array
     */
    private function saveCom(FeedbackAddRequest $request): array
    {
        $array = handleRequest($request);
        foreach ($array as $k => $v) {
            if ($k === 'fileIds') $array[$k] = $v;
            else {
                $array['fb' . ucfirst($k)] = $v;
                unset($array[$k]);
            }
        }
        return $array;
    }

    /**
     * saveImg
     * @param Model $feedback
     * @return void
     */
    private function saveImg(Model $feedback): void
    {
        if (is_null($feedback->img_id_json)) return;
        ShopImageLogic::query()->whereIn('img_id', json_decode($feedback->img_id_json, true))
            ->where(['user_main_id' => MAINID, 'img_source_type' => 2])
            ->update(['img_source_id' => $feedback->fb_id, 'img_is_cover' => 0]);
    }
}
